<template>
    <div class="radio-person" v-clickoutside="closeTreeFun">
        <section>
            <el-input v-model="personVal" :title="personVal" @focus="inputFocus" :disabled="inputDisabled" readonly :placeholder="placeholder"></el-input>
            <i class="fa fa-times radio-person-clear" @click="clearTreePop" title="清空" v-show='!inputDisabled'></i>
        </section>
        <section v-show="showTree" class='manytree'>
            <div class="input-wrap clearfix">
                <div class="group-input">
                    <el-input placeholder="选择组" v-model="filterText" @focus="focusFun"></el-input>
                    <i class="fa fa-times" @click="deleteGroup"></i>
                </div>
                <div class="staff-input">
                    <el-input placeholder="输入用户姓名" v-model="filterStaff"></el-input>
                </div>
            </div>
            <section v-show='showDept' class="content-inner">
                <el-tree 
                    ref="tree" 
                    v-show="multiple" 
                    :data="deptData" 
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    @node-click="treeClick" 
                    :highlight-current=true 
                    :filter-node-method="filterNode">
                </el-tree>
                <!--机构tree-->
                <el-tree 
                    ref="tree1" 
                    v-show="!multiple" 
                    :data="deptData" 
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode" 
                    @node-click="treeClick">
                </el-tree>
            </section>
            <ul v-show="showStaff" class="content-inner">
                <!--人员tree-->
                <el-tree 
                    ref="tree2" 
                    v-show="multiple"
                    :data="staffData" 
                    show-checkbox 
                    node-key="userId"
                    :check-on-click-node="true"
                    highlight-current 
                    :props="defaultProps"
                    @check-change="checkChange"
                    :filter-node-method="filterNode2">
                </el-tree>
                <el-tree 
                    ref="tree3"
                    v-show="!multiple" 
                    :props="defaultProps" 
                    highlight-current 
                    @node-click="nodeClick" 
                    :data="staffData"
                    :filter-node-method="filterNode2">
                </el-tree>
            </ul>
        </section>
    </div>
</template>
<script>
    import { initDeptTree, getStaffById, getUserBaseList } from "@/service/core/deptConf";
    import { getUserQuery } from '@/service/core/userMana';
    import { isArray, transformTozTreeFormat } from "@/utils/Tools";
    export default {
        name: 'selectUser', // 用户选择组件
        props: {
            multiple: { // 是否多选
                type: Boolean,
                default: false,
            },
            value: { // v-model绑定值
                type: [String, Array],
                default () {
                    if(this.multiple) {
                        return []
                    }else {
                        return ''
                    }
                }
            },
            label: { // 人员名称
                type: [String, Array],
                default() {
                    if(this.multiple) {
                        return []
                    }else {
                        return ''
                    }
                }
            },
            disabled: {
                type: Boolean,
                default: false,
            },
            placeholder: String,
        },
        inject: ['elForm'],
        watch: {
            value(val) {
                if(!this.multiple) {
                    if (!val) {
                        this.personVal = '';
                    }
                }else {
                    if(val.length == 0) {
                        this.personVal = [];
                    }
                }
            },
            filterText(val) { // 业务组过滤
                if (!this.multiple && this.$refs.tree1) {
                    this.$refs.tree1.filter(val);
                    
                } else if (this.multiple && this.$refs.tree) {
                    this.$refs.tree.filter(val);
                }
            },
            filterStaff(val) { // 人员过滤
                if (this.multiple && this.$refs.tree2) {
                    this.$refs.tree2.filter(val);
                } else if (!this.multiple && this.$refs.tree3) {
                    this.$refs.tree3.filter(val);
                }
            },
        },
        computed: {
            personVal: {
                get: function () {
                    if(!this.multiple) {
                        return this.label;
                    }else {
                        return this.label.join()
                    }
                },
                set: function (val) {
                    this.$emit("update:label", val);
                }
            },
            selected: {
                get: function() {
                    if(this.multiple) {
                        return this.value.map((val, index) => {
                            return {
                                userId: val,
                                username: this.label[index]
                            }
                        })
                    }
                },
                set: function(val) {
                    let ids = val.map(v => v.userId);
                    let labels = val.map(v => v.username);
                }
            },
            inputDisabled() {
                return this.disabled || (this.elForm || {}).disabled;
            },
        },
        data() {
            return {
                token: this.$store.state.token.token,
                deptId: this.$store.state.token.deptId,
                deptName: this.$store.state.token.deptName,
                showTree: false,
                showDept: true,
                deptData: [],
                staffData: [],
                showStaff: false,
                filterText: '',
                filterStaff: '',
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
            };
        },
        mounted() {
            this.$nextTick(() => {
                this.showDept = false;
                this.filterText = this.deptName;
                this.deptTreeInit();
                this.initgetStaffById();
            })
        },
        methods: {
            filterNode(value, data) { // 过滤机构
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            filterNode2(value, data) { // 过滤人员
                if (!value) return true;
                return data.username.indexOf(value) !== -1;
            },
            focusFun() { // 业务组焦点事件
                this.showDept = true;
                this.showStaff = false;
                this.filterStaff = '';
                this.deptTreeInit();
            },
            clearTreePop() { // 清空按钮点击
                if(!this.multiple) {
                    this.$emit('input', '');
                    this.$emit('change', {});
                    this.personVal = '';
                }else {
                    this.$emit('input', []);
                    this.personVal = [];
                }
                this.showDept = false;
                this.showStaff = false;
            },
            inputFocus() {
                this.showTree = true;
                this.$nextTick(() => {
                    if(this.multiple && this.showStaff) {
                        this.$refs.tree2 && this.$refs.tree2.setCheckedKeys(this.value, true);
                    }
                })
            },
            deptTreeInit() { // 请求机构数据
                let params = {
                    token: this.token,
                    statusId: "ACTIVE",
                    columns: 'path,orderNum',
                    orders: 'true,true'
                };
                initDeptTree(params).then(res => {
                    if (res.data.code == 1000) {
                        let data = res.data.data;
                        if(Array.isArray(data)) {
                            data = data.map(item => {
                                if (item.statusId == "ACTIVE") {
                                    return {
                                        type: "dept",
                                        id: item.id,
                                        parentId: item.parentId,
                                        label: item.name,
                                        children: []
                                    }
                                }
                            })
                            data = data.filter(v => v != undefined); // 过滤掉undefined
                            let nodes = transformTozTreeFormat(data); // 组装成嵌套结构的数据
                            this.deptData = [...nodes];
                        }
                    }
                });
            },
            initgetStaffById() { // 查询当前机构下的人员
                let params = {
                    deptId: this.deptId,
                    userStatusId: 'ACTIVE',
                    columns: 'employeeNo',
                    orders: 'ASC',
                }
                getUserQuery(params).then(res => {
                    if (res.data.code == 1000) {
                        let result = res.data.data;
                        if (Array.isArray(result)) {
                            this.staffData = result.map(item => {
                                return {
                                    ...item,
                                    type: "person",
                                    userId: item.id,
                                    username: item.username,
                                    label: `${item.username}${item.employeeNo ? '(' + item.employeeNo + ')' : ''}`,
                                    orgName: item.username,
                                    deptId: item.deptId,
                                    deptName: item.deptName,
                                    employeeNo: item.employeeNo,
                                    positionId: item.positionId,
                                    positionName: item.positionName,
                                }
                            })
                            this.$nextTick(() => {
                                if(this.multiple) {
                                    this.$refs.tree2 && this.$refs.tree2.setCheckedKeys(this.value, true);
                                }
                            })
                        }else {
                            this.staffData = [];
                        }
                    }
                    this.showDept = false;
                    this.showStaff = true;
                })
            },
            nodeClick(treeNode) { // 人员点击
                this.personVal = treeNode.username;
                this.$emit('input', treeNode.userId);
                this.$emit('change', treeNode);
                this.closeTreeFun();
            },
            treeClick(val) { // 点击tree
                this.filterStaff = '';

                if(val.id == this.deptId) {
                    if (val.type == "dept") {
                        this.filterText = val.label;
                        this.showDept = false;
                        this.showStaff = true;
                        this.$nextTick(() => {
                            if(this.multiple) {
                                this.$refs.tree2 && this.$refs.tree2.setCheckedKeys(this.value, true);
                            }
                        })
                    }
                    return
                }
                this.deptId = val.id;
                if (val.type == "dept") {
                    this.filterText = val.label;
                    this.initgetStaffById();
                }
            },
            checkChange(node, isSel) {
                let personArr = this.mergeToObj(this.value, this.label);
                if(isSel) {
                    let index = personArr.findIndex(v => v.userId == node.userId);
                    if(index == -1) {
                        personArr.push({
                            userId: node.userId,
                            username: node.username
                        })
                    }
                }else {
                    let index = personArr.findIndex(v => v.userId == node.userId);
                    if(index > -1) {
                        personArr.splice(index, 1);
                    }
                }
                
                let ids = personArr.map(v => v.userId);
                let labels = personArr.map(v => v.username);
                this.$emit('input', ids);
                this.personVal = labels;
            },
            deleteGroup() { // 删除机构
                this.filterText = '';
                this.deptId = '';
                this.showDept = false;
            },
            closeTreeFun() { // 点击空白处关闭
                this.showTree = false;
            },
            mergeToObj(arr1, arr2) {
                const zip = ([x,...xs], [y,...ys]) => {
                    if (x === undefined || y === undefined) {
                        return [];
                    }else {
                        return [[x,y], ...zip(xs, ys)];
                    }
                 }
                let result = zip(arr1, arr2).map(([userId, username]) => ({userId, username}));
                return result
            },
        }
    };

</script>
<style lang="scss" scoped>
    .radio-person {
        position: relative;

        .manytree {
            position: absolute;
            min-width: 200px;
            width: 100%;
            z-index: 1990;
            height: 250px;
            border: 1px solid #ddd;
            padding: 3px;
            background: #fff;

            .content-inner {
                height: 200px;
                overflow: auto;
                float: left;
                width: 100%;
                margin-top: 5px;
            }
        }

        .radio-person-clear {
            position: absolute;
            right: 10px;
            top: 10px;
            cursor: pointer;
        }

        /deep/ {
            .el-input__inner {
                padding-right: 28px;

            }

            .manytree .el-input__inner {
                border-color: #ddd !important;
            }
        }

        .input-wrap {

            .group-input,
            .staff-input {
                position: relative;
                float: left;
                width: 50%;

                i {
                    position: absolute;
                    top: 10px;
                    right: 10px;
                }
            }
        }

        i.fa{
            color: #000;
        }
    }

</style>
